package com.lrkj.framework.websocket.handler;

import com.lrkj.framework.websocket.WebSocketUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.websocket.server.ServerEndpoint;

@Component
public class WebSocketHandler extends TextWebSocketHandler {
    /**
     * 连接已关闭，移除在Map集合中的记录
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        WebSocketUtil.offline(session);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        WebSocketUtil.handleError(exception);
    }

    /**
     * 连接建立成功之后，记录用户的连接标识，便于后面发信息
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        WebSocketUtil.online(session);
    }

    /**
     * 处理收到的websocket信息
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        WebSocketUtil.receive(message.getPayload(), session);
    }

}
